/*
** list_func.c for List func in /home/vriely/Work/Templates/List
**
** Made by Samuel Vrielynck
** Login   <vriely_s@epitech.net>
**
** Started on  Tue Apr 17 22:03:57 2012 Samuel Vrielynck
** Last update Tue Jul 10 15:34:58 2012 pierrick druart
*/

#include	<stdlib.h>

#include	"list.h"

void		list_pop(struct s_list *this, void (*func)(void *))
{
  struct s_item	*save;

  if (this != NULL && this->head != NULL)
  {
    save = this->head->next;
    if (func != NULL)
      func(this->head->content);
    else
      free(this->head->content);
    if (this->head == this->tail)
      this->tail = save;
    free(this->head);
    this->head = save;
    this->len--;
  }
}

static void	erase_next(struct s_list *this, struct s_item *item)
{
  if (item->next != NULL)
    item->next->prev = item->prev;
  if (item->prev != NULL)
    item->prev->next = item->next;
  if (this->head == item)
    this->head = item->next;
  if (this->tail == item)
    this->tail = item->prev;
}

struct s_item	*list_erase(struct s_list *this, struct s_item *item,
    void (*f)(void *))
{
  struct s_item	*save;
  struct s_item	*cur;

  if (this != NULL && this->len != 0 && item != NULL)
  {
    cur = this->head;
    while (cur != NULL)
    {
      if (cur == item)
      {
	erase_next(this, cur);
	if (f != NULL)
	  f(cur->content);
	this->len--;
	save = cur->next;
	free(cur);
	break;
      }
      cur = cur->next;
    }
  }
  return (save);
}

void		list_for_each(struct s_list *this, void (*f)(void *, void *),
    void *user_data)
{
  struct s_item	*cur;

  if (this != NULL && f != NULL)
  {
    if (this->len != 0)
    {
      cur = this->head;
      while (cur != NULL)
      {
	f(cur->content, user_data);
	cur = cur->next;
      }
    }
  }
}
